<!--邀请用户加入租户弹窗-->
<template>
  <BasicForm @register="registerForm" ref="formRef">
    <template #link="{ model, field }">
      <div :class="[prefixCls]" v-html="model[field]"></div>
    </template>
  </BasicForm>
</template>

<script lang="ts">
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { defineComponent, onMounted, ref, unref, watch } from "vue"
  import { checkPhone, checkEmail } from "/@/utils"
  import { useMessage } from "/@/hooks/web/useMessage"
  import * as userApi from "/@/api/iam/user"
  import * as roleApi from '/@/api/iam/role'
  import { Textarea } from "ant-design-vue"
  import { useCopyToClipboard } from "/@/hooks/web/useCopyToClipboard"
  import { useDesign } from "/@/hooks/web/useDesign"
  export default defineComponent({
    name: "TenantInviteUserModal",
    components: {
      BasicModal,
      BasicForm,
      Textarea,
    },
    props: {
      invite: { type: Object, default: undefined },
    },
    emit: ["change"],
    setup(props, { emit }) {
      const { clipboardRef, copiedRef } = useCopyToClipboard()
      const { createMessage } = useMessage()
      const formRef = ref()
      let oldInvite: any = undefined
      const { prefixCls } = useDesign("invite-link")
      const [registerForm, { resetFields, validate, setFieldsValue, appendSchemaByField, removeSchemaByField }] = useForm({
        schemas: [
          {
            label: "通知用户",
            field: "toUser",
            component: "Select",
            required: false,
            defaultValue: null,
            componentProps: () => {
              return {
                placeholder: "请输入手机号/邮箱",
                mode: "tags",
                onChange: async (values) => {
                  const ret = values.filter((toUser) => !checkPhone(toUser) && !checkEmail(toUser))
                  if (ret.length > 0) {
                    createMessage.warning(`非法手机号/邮箱 ${ret.join("、")}`)
                  }
                  const userInvite = await userApi.getUserInvite({ toUser: values.join(",") })
                  emit("change", userInvite)
                },
              }
            },
          },
          {
            label: "分配角色",
            field: "assignRoleIds",
            component: "ApiSelect",
            helpMessage: '只有用户第一次加入企业才会生效, 之后重复加入不会重新分配角色',
            defaultValue: null,
            componentProps: {
              mode: "multiple",
              api: roleApi.listRole,
              labelField: "roleName",
              valueField: "id",
            },
          },
        ],
        showActionButtonGroup: false,
        labelCol: { span: 24 },
        wrapperCol: { span: 24 },
      })

      onMounted(async () => {
        await resetFields()
      })
      watch(
        () => props.invite,
        (val) => {
          if (!formRef.value) {
            return
          }
          removeSchemaByField(["link"])
          setFieldsValue({ link: undefined })
          oldInvite = val
          if (!oldInvite) {
            return
          }
          appendSchemaByField(
            {
              label: "链接地址",
              field: "link",
              component: "Input",
              slot: "link",
              defaultValue: null,
            },
            ""
          )
          const link = oldInvite.inviteLink + "   <br/>链接有效期至 " + oldInvite.endDate
          setFieldsValue({ link })
        },
        { immediate: true }
      )

      /**
       * 提交，返回给租户list页面
       */
      async function save() {
        let values = await validate()
        const toUser = values.toUser?.split(",") || []
        const checkRet = toUser.filter((toUser) => !checkPhone(toUser) && !checkEmail(toUser))
        if (checkRet.length > 0) {
          createMessage.warning(`非法手机号/邮箱 ${checkRet.join("、")}`)
          throw new Error("非法手机号/邮箱")
        }

        const resp = await userApi.saveUserInvite({ 
          toUser, domain: window.location.protocol + "//" + window.location.host, 
          assignRoleIds: values.assignRoleIds?.split(",") || []
        })
        const link = resp.inviteLink + "   <br/>链接有效期至 " + resp.endDate

        removeSchemaByField(["link"])
        setFieldsValue({ link: undefined })

        appendSchemaByField(
          {
            label: "链接地址",
            field: "link",
            component: "Input",
            slot: "link",
            defaultValue: null,
          },
          ""
        )
        setFieldsValue({ link })
        handleCopy(resp.inviteLink)
        console.log("values", values)
      }

      function handleCopy(copyValue) {
        if (!copyValue) {
          return
        }
        const value = unref(copyValue)
        if (!value) {
          createMessage.warning("请输入要拷贝的内容！")
          return
        }
        clipboardRef.value = value
        if (unref(copiedRef)) {
          createMessage.success("拷贝成功")
        }
      }

      return {
        formRef,
        prefixCls,
        registerForm,
        save,
      }
    },
  })
</script>

<style scoped lang="less">
  @prefix-cls: ~"@{namespace}-invite-link";

  .@{prefix-cls} {
    height: 100px;
    padding: 10px;
    border-radius: 5px;
    /* 设置为灰色背景 */
    background-color: #f0f0f0;
    /* 禁用时输入框颜色 */
    color: #666;
  }
</style>
